// pages/category/category.js
import {
    testrequest
} from "../../request/index.js"
import regeneratorRuntime from '../../lib/runtime/runtime';

import {
    getSetting,
    chooseAddress,
    openSetting,
    showModal,
    showToast
} from "../../utils/asyncWx.js";
Page({

    /**
     * 页面的初始数据
     */
    data: {
        resName: "餐厅名（光谷店）",
        tabID: "A07",

        array: [1, 2, 3, 4, 5, 6, 7, 8],
        num: 1, //就餐人数

        //传入菜品分类：
        leftMenuList: [],
        rightContent: [],
        currentIndex: 0,
        scrollTop: 0,

        address: {},
        cart: [],
        allChecked: false,
        totalPrice: 0,
        totalDishNum: 0,

        showCartPop: false,
        showNumChk: true,
    },
    // 接口返回数据
    Cates: [],

    onLoad: function (options) {
        //获取本地存储
        const Cates = wx.getStorageSync("cates");
        const spireTime = 10000 //过期时间
        if (!Cates || Date.now() - Cates.time > spireTime) {
            this.getCates();
        } else {
            this.Cates = Cates.data;
            let leftMenuList = this.Cates.map(v => v.cat_name); //map是遍历函数
            let rightContent = this.Cates[0].children;
            this.setData({
                leftMenuList,
                rightContent
            })
        }
    },

    // 获取商品分类数据
    async getCates() {
        testrequest({
                url: "/categories"
            })
            .then(res => {
                this.Cates = res;
                wx.setStorageSync("cates", {
                    time: Date.now(),
                    data: this.Cates
                })
                let leftMenuList = this.Cates.map(v => v.cat_name); //map是遍历函数
                let rightContent = this.Cates[0].children;
                this.setData({
                    leftMenuList,
                    rightContent
                })
            })

        //使用es7的async await发送请求
        // const res = await testrequest({ url: "/categories" });
        // this.Cates = res;
        // wx.setStorageSync("cates", { time: Date.now(), data: this.Cates })
        // let leftMenuList = this.Cates.map(v => v.cat_name);//map是遍历函数
        // let rightContent = this.Cates[0].children;
        // this.setData({ leftMenuList, rightContent })
    },

    //  左侧栏点击切换
    handleItemTap(e) {
        const {
            index
        } = e.currentTarget.dataset;
        let rightContent = this.Cates[index].children;
        this.setData({
            currentIndex: index,
            rightContent,
            scrollTop: 0
        })

    },

    // 当页面发生更改时，总价总量全选状态需要重新计算
    setCart(cart) {
        let allChecked = true;
        let totalPrice = 0;
        let totalDishNum = 0;
        cart.forEach(v => {
            if (v.checked) {
                totalPrice += v.num * v.goods_price;
                totalDishNum += v.num;
            } else {
                allChecked = false;
            }
        })
        if (cart.length === 0)
            allChecked = false;
        this.setData({
            cart,
            allChecked,
            totalDishNum,
            totalPrice
        });
        wx.setStorageSync('cart', cart);
    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        const address = wx.getStorageSync('address');
        const cart = wx.getStorageSync('cart') || [];
        //const allChecked=cart.length?cart.every(v=>v.checked):false;//必须每个遍历item都为true才能返回true,空数组返回值是true
        this.setData({
            address
        });
        this.setCart(cart);
    },

    // 每个商品的选择框
    handleItemChange(e) {
        const goods_id = e.currentTarget.dataset.id;
        // 获取购物车数组
        let {
            cart
        } = this.data;
        // 获取该商品在购物车中的索引
        let index = cart.findIndex(v => v.goods_id == goods_id);
        // 索引取反
        cart[index].checked = !cart[index].checked;
        this.setCart(cart);
    },

    // 数量控制
    async handleItemNumEdit(e) {
        const {
            id,
            operation
        } = e.currentTarget.dataset;
        let {
            cart
        } = this.data;
        let index = cart.findIndex(v => v.goods_id === id);
        if (cart[index].num === 1 && operation === -1) {
            const res = await showModal({
                content: "您是否要删除？",
            });
            if (res.confirm) {
                cart.splice(index, 1);
                this.setCart(cart);
            }
        } else {
            cart[index].num += operation;
            this.setCart(cart);
        }

    },

    //点击我显示底部弹出框
    clickme: function () {
        this.showModal();
    },

    //显示对话框
    showModal: function () {
        // 显示遮罩层
        var animation = wx.createAnimation({
            duration: 200,
            timingFunction: "linear",
            delay: 0
        })
        this.animation = animation
        animation.translateY(300).step()
        this.setData({
            animationData: animation.export(),
            showModalStatus: true
        })
        setTimeout(function () {
            animation.translateY(0).step()
            this.setData({
                animationData: animation.export()
            })
        }.bind(this), 200)
    },
    //隐藏对话框
    hideModal: function () {
        // 隐藏遮罩层
        var animation = wx.createAnimation({
            duration: 200,
            timingFunction: "linear",
            delay: 0
        })
        this.animation = animation
        animation.translateY(300).step()
        this.setData({
            animationData: animation.export(),
        })
        setTimeout(function () {
            animation.translateY(0).step()
            this.setData({
                animationData: animation.export(),
                showModalStatus: false
            })
        }.bind(this), 200)
    },

    bindPickerChange: function (e) {
        const index = e.detail.value;
        console.log('picker发送选择改变，携带值为', e.detail.value)
        this.setData({
            num: this.data.array[index],
        })
        console.log("人数num=" + this.data.num);
    },

    handleNumChoosed: function () {
        console.log(this.data.showNumChk)
        this.setData({
            showNumChk: false
        })
        console.log(this.data.showNumChk)

    }


})